﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace 凯旋归来管理端.models
{
    public class 怪物掉宝
    {
        public int Id;
        public string 区域名称;
        public string 掉落物品;
        public static 怪物掉宝[] 数据表转数组(DataTable dt)
        {
            怪物掉宝[] ret = new 怪物掉宝[dt.Rows.Count];
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                ret[i] = new 怪物掉宝();
                int.TryParse(dt.Rows[i]["id"].ToString(), out ret[i].Id);
                ret[i].区域名称 = dt.Rows[i]["区域名称"].ToString();
                ret[i].掉落物品 = dt.Rows[i]["掉落物品"].ToString();
            }
            return ret;
        }
        public string 保存已有行(string connstr,string 原名称)
        {

            string sql = "UPDATE 怪物掉宝 SET 区域名称=@0,掉落物品=@1 WHERE id=@2";
            using (MySqlConnection conn = new MySqlConnection(connstr))
            {
                try
                {
                    conn.Open();
                    MySqlCommand cmd = new MySqlCommand(sql, conn);
                    cmd.Parameters.AddWithValue("@0", this.区域名称);
                    cmd.Parameters.AddWithValue("@1", this.掉落物品);
                    cmd.Parameters.AddWithValue("@2", this.Id);
                    cmd.ExecuteNonQuery();

                    if (原名称 != this.区域名称)
                    {
                        sql = "UPDATE 怪物生成表 SET 区域名称=@0 WHERE 区域名称=@1";
                        cmd = new MySqlCommand(sql, conn);
                        cmd.Parameters.AddWithValue("@0", this.区域名称);
                        cmd.Parameters.AddWithValue("@1", 原名称);
                        cmd.ExecuteNonQuery();
                    }
                }
                catch (Exception ex)
                {
                    return ex.ToString(); ;
                }
                finally
                {
                    conn.Close();
                }
            }
            return "";
        }
        public string 新建区域(string connstr)
        {

            string sql = "INSERT INTO 怪物掉宝 (区域名称,掉落物品)VALUE(@0,@1)";
            using (MySqlConnection conn = new MySqlConnection(connstr))
            {
                try
                {
                    conn.Open();
                    MySqlCommand cmd = new MySqlCommand(sql, conn);
                    cmd.Parameters.AddWithValue("@0", this.区域名称);
                    cmd.Parameters.AddWithValue("@1", this.掉落物品);
                    cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    return ex.ToString(); ;
                }
                finally
                {
                    conn.Close();
                }
            }
            return "";
        }
    }
}
